package com.action;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import com.bean.InstrumentBean;
import com.bean.RecordBean;
import com.bean.UserBean;
import com.dao.BorrowInsDao;
import com.dao.InstrumentDao;
import com.dao.UserDao;
import com.exception.BorrowException;
import com.exception.DBException;
import com.exception.InstrumentException;
import com.exception.UserException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BorrowAction
{
	private void BEAN_JSON_SEND(HttpServletResponse response,
			ArrayList<RecordBean> list)
	{
		Gson gson = new GsonBuilder().setDateFormat("MM-dd-yyyy").create();
		String json = gson.toJson(list);
		response.setContentType("application/json");
		try
		{
			Writer w = response.getWriter();
			w.write(json);
			w.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	public void borrowIns(HttpServletResponse response, RecordBean recordBean)
			throws UserException, DBException, InstrumentException,
			BorrowException
	{
		UserBean userBean = new UserBean();
		UserDao userDao = new UserDao();
		userBean.setUserID(recordBean.getUserID());
		if (!userDao.ifUserExist(userBean))
		{
			throw new UserException("User is not exist!");
		}

		InstrumentBean insBean = new InstrumentBean();
		insBean.setBarcode(recordBean.getBarcode());
		InstrumentDao insDao = new InstrumentDao();
		if (!insDao.ifInsExist(insBean))
		{
			throw new InstrumentException("Instrument is not exist!");
		}
		if("no".equals(insDao.ifInsBorrowed(insBean)))
		{
			throw new InstrumentException("Instrument is already borrowed!");
		}
		
		BorrowInsDao borrowInsDao = new BorrowInsDao();
		borrowInsDao.borrowRecord(recordBean);
		ArrayList<RecordBean> list = borrowInsDao.getBorrowResult(recordBean);

		this.BEAN_JSON_SEND(response, list);
	}

}
